package homework.chatthree;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class ChatClientThree01 {
    private Socket socket;


    public ChatClientThree01() {
        try {
            socket = new Socket("127.0.0.1", 8888);
            System.out.println("连接成功...");
        } catch (IOException e) {
            System.out.println("连接失败...");
            e.printStackTrace();
            System.exit(-1);
        }
    }

    class BRClientThread implements Runnable{
        BufferedReader br = null;

        @Override
        public void run() {
            try {
                while (true) {
                    br = new BufferedReader(
                            new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));

                    String data;
                    while ((data=br.readLine())!=null){
                        System.out.println(data);
                    }

                }
            } catch (IOException e) {
                try {
                    br.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }


        }
    }

    private void start() {
        Scanner scanner = new Scanner(System.in);
        PrintWriter pw = null;

        try {
            pw = new PrintWriter(
                    new BufferedWriter(
                            new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8)), true);

            while (true){
                System.out.println("请输入用户名:");
                String userName=scanner.nextLine();
                if (userName==null){
                    System.out.println("用户名不能为空");
                    continue;
                }
                pw.println(userName);
                break;
            }

            new Thread(new BRClientThread()).start();

            while (true){
                System.out.println("输入发送内容");
                String str = scanner.nextLine();

                if ("exit".equalsIgnoreCase(str)){
                    System.out.println("退出成功");
                    break;
                }
                pw.println(str);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                pw.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        new ChatClientThree01().start();
    }

}
